<template>
  <div class="task-scheduler">
    <el-card class="scheduler-card" shadow="hover">
      <div slot="header" class="card-header">
        <div class="header-left">
          <i class="el-icon-time"></i>
          <span>计划任务</span>
          <el-tooltip content="计划任务用于设置主机定时开关机等操作" placement="right">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <el-button type="primary" @click="showTaskConfigDialog" icon="el-icon-plus">任务配置</el-button>
      </div>

      <!-- 批量操作和搜索栏 -->
      <div class="operation-bar">
        <div class="left-operations">
          <el-button-group>
            <el-button
              size="small"
              :disabled="!selectedTasks.length"
              @click="handleBatchEnable">
              批量生效
            </el-button>
            <el-button
              size="small"
              :disabled="!selectedTasks.length"
              @click="handleBatchPause">
              批量暂停
            </el-button>
            <el-button
              size="small"
              type="danger"
              :disabled="!selectedTasks.length"
              @click="handleBatchDelete">
              批量删除
            </el-button>
          </el-button-group>
        </div>
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="请输入搜索关键字"
            prefix-icon="el-icon-search"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch">
          </el-input>
        </div>
      </div>

      <!-- 任务列表 -->
      <el-table
        :data="filteredTableData"
        style="width: 100%"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange"
        element-loading-text="加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)"
        stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="enterprise" label="企业名称" min-width="150">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.enterprise" placement="top">
              <span class="enterprise-name">{{ scope.row.enterprise }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="hostAddress" label="主机地址" min-width="140">
          <template slot-scope="scope">
            <span class="host-address">{{ scope.row.hostAddress }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="strategy" label="策略详情" min-width="180">
          <template slot-scope="scope">
            <span class="strategy-text">{{ scope.row.strategy }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cycle" label="操作周期" width="120">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.cycle === '重复执行' ? 'success' : 'info'">
              {{ scope.row.cycle }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="策略状态" width="100">
          <template slot-scope="scope">
            <div class="status-cell">
              <span
                class="status-dot"
                :class="{
                  'active': scope.row.status === '生效',
                  'paused': scope.row.status === '暂停',
                  'inactive': scope.row.status === '失效'
                }">
              </span>
              {{ scope.row.status }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.remarks || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="handleModify(scope.row)">修改</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button
              type="text"
              :class="scope.row.status === '生效' ? 'pause-button' : 'enable-button'"
              @click="handleToggleStatus(scope.row)">
              {{ scope.row.status === '生效' ? '暂停' : '生效' }}
            </el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button
              type="text"
              class="delete-button"
              @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <span class="total-count">共 {{ total }} 条数据</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 任务配置对话框 -->
    <el-dialog
      :title="isEdit ? '修改任务' : '任务配置'"
      :visible.sync="taskDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @closed="resetTaskForm">
      <el-form :model="taskForm" :rules="taskRules" ref="taskForm" label-width="120px">
        <el-form-item label="定时任务" required>
          <span class="task-type-text">主机定时开关机</span>
        </el-form-item>
        <el-form-item label="主机地址(公网)" prop="hostAddress" required>
          <el-select
            v-model="taskForm.hostAddress"
            placeholder="请选择主机"
            filterable
            style="width: 100%">
            <el-option
              v-for="host in hostOptions"
              :key="host.value"
              :label="host.label"
              :value="host.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType" required>
          <el-radio-group v-model="taskForm.taskType">
            <el-radio label="start">开机</el-radio>
            <el-radio label="shutdown">关机</el-radio>
            <el-radio label="restart">重启</el-radio>
          </el-radio-group>
          <div class="form-tip" v-if="taskForm.taskType === 'restart'">
            （关机状态下，重启任务将经略）
          </div>
        </el-form-item>
        <el-form-item label="执行周期" prop="executionCycle" required>
          <el-radio-group v-model="taskForm.executionCycle">
            <el-radio label="once">执行一次</el-radio>
            <el-radio label="repeat">重复执行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="开机时间"
          prop="startTime"
          required>
          <el-date-picker
            v-model="taskForm.startTime"
            type="datetime"
            placeholder="请选择日期时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务生效时间" prop="effectiveTime" required>
          <el-radio-group v-model="taskForm.effectiveTime">
            <el-radio label="immediate">立即生效</el-radio>
            <el-radio label="custom">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务截止时间" prop="endTime" required>
          <el-radio-group v-model="taskForm.endTime">
            <el-radio label="unlimited">无限期</el-radio>
            <el-radio label="custom">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            type="textarea"
            :rows="4"
            v-model="taskForm.remarks"
            placeholder="请输入备注信息">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="taskDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleTaskSubmit" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      :title="batchDelete ? '批量删除确认' : '删除确认'"
      :visible.sync="deleteDialogVisible"
      width="400px">
      <div class="delete-confirm-content">
        <i class="el-icon-warning"></i>
        <p>{{ batchDelete ?
          `确定要删除选中的 ${selectedTasks.length} 个任务吗？` :
          '确定要删除该任务吗？' }}此操作不可恢复。</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="confirmDelete" :loading="deleting">确定删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TaskScheduler',
  data() {
    return {
      // 搜索相关
      searchQuery: '',
      loading: false,

      // 表格数据
      tableData: [
        {
          enterprise: '发票兔****50',
          hostAddress: '39.99.137.75',
          strategy: '每天 07:00重启',
          cycle: '重复执行',
          status: '生效',
          remarks: '执行日志测试',
          createTime: '2024-02-29'
        }
      ],

      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 1,

      // 选择相关
      selectedTasks: [],

      // 任务配置对话框
      taskDialogVisible: false,
      isEdit: false,
      submitting: false,
      taskForm: {
        hostAddress: '',
        taskType: 'start',
        executionCycle: 'once',
        startTime: '',
        effectiveTime: 'immediate',
        endTime: 'unlimited',
        remarks: ''
      },
      taskRules: {
        hostAddress: [
          { required: true, message: '请选择主机地址', trigger: 'change' }
        ],
        taskType: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        executionCycle: [
          { required: true, message: '请选择执行周期', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开机时间', trigger: 'change' }
        ]
      },

      // 主机选项
      hostOptions: [
        { value: '39.99.137.75', label: '39.99.137.75' },
        { value: '39.98.90.201', label: '39.98.90.201' }
      ],

      // 删除相关
      deleteDialogVisible: false,
      deleting: false,
      batchDelete: false,
      currentDeleteItem: null
    }
  },
  computed: {
    filteredTableData() {
      if (!this.searchQuery) {
        return this.tableData
      }
      const query = this.searchQuery.toLowerCase()
      return this.tableData.filter(data => {
        return data.enterprise.toLowerCase().includes(query) ||
          data.hostAddress.includes(query) ||
          data.strategy.toLowerCase().includes(query) ||
          (data.remarks && data.remarks.toLowerCase().includes(query))
      })
    }
  },
  methods: {
    // 搜索相关方法
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 选择相关方法
    handleSelectionChange(val) {
      this.selectedTasks = val
    },

    // 批量操作方法
    handleBatchEnable() {
      this.selectedTasks.forEach(task => {
        if (task.status !== '生效') {
          task.status = '生效'
        }
      })
      this.$message.success('批量生效成功')
    },
    handleBatchPause() {
      this.selectedTasks.forEach(task => {
        if (task.status === '生效') {
          task.status = '暂停'
        }
      })
      this.$message.success('批量暂停成功')
    },
    handleBatchDelete() {
      this.batchDelete = true
      this.deleteDialogVisible = true
    },

    // 任务配置相关方法
    showTaskConfigDialog() {
      this.isEdit = false
      this.taskDialogVisible = true
    },
    resetTaskForm() {
      if (this.$refs.taskForm) {
        this.$refs.taskForm.resetFields()
      }
      this.taskForm = {
        hostAddress: '',
        taskType: 'start',
        executionCycle: 'once',
        startTime: '',
        effectiveTime: 'immediate',
        endTime: 'unlimited',
        remarks: ''
      }
    },
    handleTaskSubmit() {
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          this.submitting = true
          // 模拟API调用
          setTimeout(() => {
            this.submitting = false
            this.taskDialogVisible = false
            this.$message({
              message: this.isEdit ? '任务修改成功' : '任务配置成功',
              type: 'success'
            })
            this.getList()
          }, 1000)
        }
      })
    },

    // 操作相关方法
    handleModify(row) {
      this.isEdit = true
      this.taskForm = { ...row }
      this.taskDialogVisible = true
    },
    handleToggleStatus(row) {
      row.status = row.status === '生效' ? '暂停' : '生效'
      this.$message({
        message: `任务${row.status === '生效' ? '生效' : '暂停'}成功`,
        type: 'success'
      })
    },
    handleDelete(row) {
      this.batchDelete = false
      this.currentDeleteItem = row
      this.deleteDialogVisible = true
    },
    confirmDelete() {
      this.deleting = true
      // 模拟API调用
      setTimeout(() => {
        this.deleting = false
        this.deleteDialogVisible = false
        if (this.batchDelete) {
          this.selectedTasks.forEach(task => {
            const index = this.tableData.indexOf(task)
            if (index > -1) {
              this.tableData.splice(index, 1)
            }
          })
          this.selectedTasks = []
        } else {
          const index = this.tableData.indexOf(this.currentDeleteItem)
          if (index > -1) {
            this.tableData.splice(index, 1)
          }
        }
        this.$message({
          message: this.batchDelete ? '批量删除成功' : '删除成功',
          type: 'success'
        })
      }, 1000)
    },

    // 获取列表数据
    getList() {
      this.loading = true
      // 模拟API调用
      setTimeout(() => {
        this.loading = false
      }, 800)
    }
  },
  created() {
    this.getList()
  }
}
</script>

<style scoped>
.task-scheduler {
  padding: 10px;
}

.scheduler-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-left i {
  font-size: 18px;
}

.header-left .el-icon-question {
  font-size: 14px;
  color: #909399;
  cursor: help;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-operations {
  display: flex;
  gap: 10px;
}

.search-box {
  width: 300px;
}

.enterprise-name {
  color: #606266;
}

.host-address {
  font-family: monospace;
  color: #409EFF;
}

.strategy-text {
  color: #606266;
}

.status-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #909399;
}

.status-dot.active {
  background-color: #67C23A;
}

.status-dot.paused {
  background-color: #E6A23C;
}

.status-dot.inactive {
  background-color: #F56C6C;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: bold;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}

/* 按钮样式 */
.delete-button {
  color: #F56C6C;
}

.pause-button {
  color: #E6A23C;
}

.enable-button {
  color: #67C23A;
}

/* 表单提示样式 */
.form-tip {
  font-size: 12px;
  color: #E6A23C;
  margin-top: 4px;
}

.task-type-text {
  color: #606266;
}

/* 删除确认对话框样式 */
.delete-confirm-content {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 20px 0;
}

.delete-confirm-content i {
  font-size: 24px;
  color: #E6A23C;
}

.delete-confirm-content p {
  margin: 0;
  color: #606266;
}

/* 对话框样式优化 */
.el-dialog__header {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

.el-dialog__footer {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
}

.el-dialog__body {
  padding: 30px 20px;
}

/* 加载动画样式 */
.el-loading-spinner .el-icon-loading {
  font-size: 30px;
  color: #409EFF;
}

.el-loading-spinner .el-loading-text {
  color: #409EFF;
  margin: 3px 0;
  font-size: 14px;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}
</style>
